const fs = require('fs');
const path = require('path');

const UPLOAD_DIR = path.join(__dirname, '../api/services');
const SERVICES_DIR = path.join(__dirname, '../api');

// 确保上传目录存在
if (!fs.existsSync(UPLOAD_DIR)) {
    fs.mkdirSync(UPLOAD_DIR, { recursive: true });
}

// 递归获取目录结构
const getDirectoryTree = (dir) => {
    const items = fs.readdirSync(dir);
    return items.map((item) => {
        const fullPath = path.join(dir, item);
        const stats = fs.statSync(fullPath);
        return {
            label: item,
            path: fullPath.replace(UPLOAD_DIR, ""),
            type: stats.isDirectory() ? "folder" : "file",
            children: stats.isDirectory() ? getDirectoryTree(fullPath) : [],
        };
    });
};

exports.getDirectories = (req, res) => {
    try {
        const tree = getDirectoryTree(UPLOAD_DIR);
        res.json({ tree });
    } catch (error) {
        res.status(500).json({ error: "无法获取目录" });
    }
};

exports.download = (req, res) => {
    const { filePath } = req.query;
    const absolutePath = path.join(UPLOAD_DIR, filePath);

    if (fs.existsSync(absolutePath) && fs.statSync(absolutePath).isFile()) {
        const fileName = path.basename(absolutePath);
        //res.download(absolutePath, path.basename(absolutePath));
        res.setHeader("Content-Disposition", `attachment; filename=${fileName}`);
        res.setHeader("Content-Type", "application/octet-stream");

        fs.createReadStream(absolutePath).pipe(res);
    } else {
        res.status(404).json({ error: "文件不存在" });
    }
}

exports.openFile = (req, res) => {
    const { filePath } = req.query;
    const absolutePath = path.join(UPLOAD_DIR, filePath);

    if (fs.existsSync(absolutePath) && fs.statSync(absolutePath).isFile()) {
        res.sendFile(absolutePath);
    } else {
        res.status(404).json({ error: "文件不存在" });
    }
}

// 📂 获取文件列表
exports.getFiles = (req, res) => {
    const targetPath = path.join(UPLOAD_DIR, req.query.path || '');
    if (!fs.existsSync(targetPath)) {
        return res.status(404).json({ message: '路径不存在' });
    }
    const files = fs.readdirSync(targetPath).map(file => {
        const filePath = path.join(targetPath, file);
        return {
            name: file,
            isDirectory: fs.statSync(filePath).isDirectory()
        };
    });
    res.json({ path: req.query.path || '', files });
};

// 📁 创建新文件夹
exports.createFolder = (req, res) => {
    const { parentDir, newFolderName } = req.body;
    const targetDir = parentDir ? path.join(UPLOAD_DIR, parentDir) : UPLOAD_DIR;
    const newFolderPath = path.join(targetDir, newFolderName);

    if (!newFolderName) return res.status(400).json({ error: "文件夹名称不能为空" });
    if (!fs.existsSync(targetDir)) return res.status(400).json({ error: "目标目录不存在" });
    if (fs.existsSync(newFolderPath)) return res.status(400).json({ error: "文件夹已存在" });

    fs.mkdirSync(newFolderPath);
    res.json({ message: "文件夹创建成功" });
};

// 📤 文件上传
exports.uploadFile = (req, res) => {
    const targetPath = path.join(UPLOAD_DIR, req.query.targetDir || '');
    if (!fs.existsSync(targetPath)) {
        return res.status(400).json({ message: '目标路径不存在' });
    }

    Object.keys(req.files).forEach(fileKey => {
        const file = req.files[fileKey];
        const newFilePath = path.join(targetPath, file.name);
        fs.renameSync(file.path, newFilePath);
    });

    res.json({ message: '文件上传成功' });
};


exports.deleteItem = (req, res) => {
    const { targetPath } = req.body;
    if (!targetPath) return res.status(400).json({ error: "文件夹名称不能为空" });
    const fullPath = path.join(UPLOAD_DIR, targetPath);

    if (!fs.existsSync(fullPath)) {
        return res.status(404).json({ error: "文件或文件夹不存在" });
    }

    try {
        const deleteRecursive = (filePath) => {
            if (fs.statSync(filePath).isDirectory()) {
                fs.readdirSync(filePath).forEach((file) => {
                    deleteRecursive(path.join(filePath, file));
                });
                fs.rmdirSync(filePath);
            } else {
                fs.unlinkSync(filePath);
            }
        };

        deleteRecursive(fullPath);
        res.json({ message: "删除成功" });
    } catch (error) {
        res.status(500).json({ error: "删除失败" });
    }
};

// 解析请求并返回本地 JSON 数据
exports.service =(req, res) => {
    const { method, path: requestPath, query, fields, cookies, params } = req;
    console.log(`Request: ${method} ${requestPath}`, { query, fields, cookies, params });

    const jsonFilePath = path.join(SERVICES_DIR, requestPath + '.json');
    if (fs.existsSync(jsonFilePath)) {
        const data = fs.readFileSync(jsonFilePath, 'utf-8');
        return res.json(JSON.parse(data));
    }

    res.status(404).json({ error: 'Mock data not found' });
}